const {
  UserProxy
} = require('../proxys')
const util = require('../utils')
module.exports = class UserController {
  static async login (ctx) {
    const { account, password } = ctx.request.body
    ctx.type = 'json'
    if (!account || !password) {
      ctx.status = 400
      ctx.body = {
        code: -1,
        msg: '请输入用户名或密码'
      }
      return
    }
    const result = await UserProxy.findOne(account)
    if (result === null || (result && !util.bcompare(password, result.password))) {
      ctx.status = 400
      ctx.body = {
        code: -1,
        msg: '用户名或密码错误'
      }
      return
    }
    ctx.status = 200
    ctx.body = {
      code: 1,
      msg: '登录成功'
    }
  }
  static async register (ctx) {
    const account = '***'
    let password = '*****'
    password = util.bhash(password)
    const result = await UserProxy.findOne({ account })
    if (result) {
      ctx.status = 400
      ctx.body = {
        code: -1,
        msg: '用户已存在'
      }
      return
    }
    try {
      await UserProxy.newAndSave(account, password)
    } catch (e) {
      ctx.throw(e)
    }
    ctx.body = {
      code: 0,
      msg: '用户添加成功'
    }
  }
}
